﻿CREATE PROCEDURE [audit].[DeleteTraceFiles]
@TracePath NVARCHAR (512)
AS
BEGIN
	SET NOCOUNT ON

	IF(@TracePath IS NULL)
		BEGIN
			RAISERROR('Invalid trace path',16,1)
			RETURN(@@ERROR)
		END
	
	SET @TracePath = ISNULL(
		NULLIF(
			SUBSTRING(@TracePath, 0, PATINDEX(N'%_[0-9]%', @TracePath)),
		N'')
	,@TracePath)
	
	PRINT 'Deleting trace files...'

	DECLARE @RC int
	SET  @RC = 0

	DECLARE @CmdStatement nvarchar(1024)
	SET @CmdStatement = 'DEL "' + @TracePath + '*.trc"'
	EXEC @RC = [master].[dbo].[xp_cmdshell] @CmdStatement, NO_OUTPUT

	IF (@RC <> 0)
		RAISERROR('Failed to delete trace file (%s)',16,1,@TracePath)
	ELSE
		PRINT 'Trace file deleted successfully'

	RETURN(@RC)
END